<template>
  <div>
    <!--新增界面-->
    <el-dialog title="复制并新增方案" :visible.sync="dialogVisible" v-loading.fullscreen.lock="loading" element-loading-text="处理中......" size="large" :close-on-click-modal="false" :close-on-press-escape="false" :before-close="off" :top="dialog_margin_top">
      <el-form label-width="160px">
        <el-row :span="24">
          <el-col :span="8">
            <el-form-item label="方案类型" required>
              <el-select v-model="formData.plantype" filterable size="small" @change="setDefault()">
                <el-option v-for="item in planTypeOptions" :key="item.value" :label="item.label" :value="item.value"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="险种代码" required>
              <el-select v-model="formData.risk" filterable value-key="riskcode" size="small" @change="newPlanCode()">
                <el-option v-for="item in riskOptions" :key="item.riskcode" :label="item.riskcode + '-' + item.riskcname" :value="item"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="是否自动核保" required>
              <el-select v-model="formData.autoundwrt" filterable size="small">
                <el-option v-for="item in autoUndwrtOptions" :key="item.value" :label="item.label" :value="item.value"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="方案有效性" required>
              <el-select v-model="formData.validstatus" size="small">
                <el-option v-for="item in validOptions" :key="item.value" :label="item.label" :value="item.value"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="方案中文名称" required>
              <el-input v-model="formData.plancname" size="small"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">

            <el-form-item label="方案英文名称" required>
              <el-input v-model="formData.planename" size="small" :maxlength="255"></el-input>
            </el-form-item>
            <el-form-item label="行程目的地">
              <el-input v-model="formData.traveldestination" size="small" :maxlength="500"></el-input>
            </el-form-item>
            <el-form-item label="职业分类代码">
              <el-input v-model="formData.occupationcode" size="small" :maxlength="10"></el-input>
            </el-form-item>
            <el-form-item label="条款是否允许删除" required>
              <el-select v-model="formData.delflag" :disabled="disabledGroup.delflag" size="small">
                <el-option v-for="item in delFlagOptions" :key="item.value" :label="item.label" :value="item.value"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="费率因子" required>
              <el-button type="warning" size="small" @click="addPropsGroup">添加因子组</el-button>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="预设保险期限方式">
              <el-select v-model="formData.periodtype" size="small">
                <el-option v-for="item in periodTypeOptions" :key="item.value" :label="item.label" :value="item.value"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="预设保险期限值">
              <el-input v-model="formData.period" size="small" :maxlength="5" @keyup.native="checkNumber(15, 'period')"></el-input>
            </el-form-item>
            <el-form-item label="方案权限适用机构" required>
              <el-input type="textarea" v-model="comLabel" size="small" readonly @dblclick.native="openPlan2CompanyDialog()"></el-input>
            </el-form-item>
            <el-form-item label="方案权限适用渠道">
              <el-input type="textarea" v-model="formData.applychannel" size="small" readonly @dblclick.native="openPlan2AgentDialog()"></el-input>
            </el-form-item>
            <el-form-item label="自动单证审核通过" required>
              <el-select v-model="formData.autodoc" filterable size="small" >
                <el-option v-for="item in autoDocOptions" :key="item.value" :label="item.label" :value="item.value"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <!-- ############################# 费率因子 ############################## -->
      <div v-for="(obj,k) in formData.propsGroup">
        <label style="font-size: 15px;color: black;font-weight:bold;">
          因子组【{{k}}】
        </label>
        <el-button type="danger" size="mini" @click="delPropsGroup(k)">删除</el-button>
        <hr>
        <el-table class="production_table" :data="obj" border style="width: 100%;" :highlight-current-row="true">
          <el-table-column prop="propscname" label="序号" min-width="12">
            <template scope="scope">
              {{scope.row.rowId}}
            </template>
          </el-table-column>
          <el-table-column prop="propscname" label="因子" min-width="20">
            <template scope="scope">
              <select :id="'propscname'+ k + scope.row.rowId"></select>
            </template>
          </el-table-column>
          <el-table-column prop="propstype" label="类型" min-width="20">
            <template scope="scope">
              <select :id="'propstype'+ k + scope.row.rowId" @change="propsTypeChange(k,scope.row)">
                <option value="0">固定值</option>
                <option value="1">区间值</option>
              </select>
            </template>
          </el-table-column>
          <el-table-column prop="propsvalue" label="值" min-width="120">
            <template scope="scope">
              <div :id="'single'+ k +scope.row.rowId">
                <input :id="'propsvalue'+ k + scope.row.rowId" size="90"></input>
              </div>
              <div :id="'multi'+ k +scope.row.rowId" style="display:none">
                <input :id="'startvalue'+ k + scope.row.rowId"></input> 至
                <input :id="'endvalue'+ k + scope.row.rowId"></input>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="操作" min-width="20" fixed="right">
            <template scope="scope">
              <el-button size="mini" type="danger" @click="delProps(k,scope.row.rowId)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-form label-width="150px">
          <el-row :span="24">
            <el-col :span="22">
              <label style="font-size: 15px;color: black;font-weight:bold;">* 条款代码：</label>
              <input :id="'kindcodesLabel' + k" v-model="formData.kindcodesGroup[k]" @click="openRiskKindSelect2Dialog(k)"></input>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
              <label style="font-size: 15px;color: black;font-weight:bold;">责任代码：</label>
              <input :id="'itemcodesLabel' + k" v-model="formData.itemcodesGroup[k]" @click="openItemCodeSelect2Dialog(k)"></input>
            </el-col>
            <el-col :span="2">
              <el-button type="text" size="small" @click="addProps(k)">添加因子项</el-button>
            </el-col>
          </el-row>
        </el-form>
        <hr>
        <br>
      </div>
      <!-- ############################# 费率因子-end ############################## -->
      <br><br>
      <div align="center" v-if="formData.kindsGroup.length !== 0">
        <label style="font-size: 18px;color: black;font-weight:bold;">
          保额保费配置
        </label><br>
        <i class="fa fa-angle-double-down fa-4" aria-hidden="true"></i>
      </div>
      <br><br>

      <div v-for="(obj,k) in formData.kinditemsGroup">
        <label style="font-size: 15px;color: red;font-weight:bold;">因子组【{{k}}】- 【保额保费配置】</label>
        <hr>
        <el-row type="flex" :span="24" justify="space-around">
          <el-col :span="24">
            <el-table :data="obj" border style="width: 100%;" :highlight-current-row="true">
              <el-table-column prop="kindcode" label="条款代码" width="130"></el-table-column>
              <el-table-column prop="kindcname" label="条款名称" show-overflow-tooltip width="300"></el-table-column>
              <el-table-column prop="itemcode" label="标的责任代码" width="130"></el-table-column>
              <el-table-column prop="itemcname" label="标的责任名称" show-overflow-tooltip min-width="400"></el-table-column>
              <el-table-column prop="oper" label="保额保费" width="150">
                <template scope="props">
                  <el-button type="default" size="small" @click="openAmountPremiumAddDialog(props.row, k)">
                    <i class="fa fa-arrow-right"></i> 配置</el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-col>
        </el-row>
        <hr>
        <br>
      </div>

      <span slot="footer" class="dialog-footer">
        <el-button @click="off">取 消</el-button>
        <el-button type="warning" @click="add2">保 存</el-button>
      </span>
    </el-dialog>
    <RiskKindSelect2 v-if="showRiskKindSelect2Dialog"></RiskKindSelect2>
    <ItemCodeSelect2 v-if="showItemCodeSelect2Dialog"></ItemCodeSelect2>
    <AmountPremiumAdd v-if="showAmountPremiumAddDialog"></AmountPremiumAdd>
    <ComSelect v-if="showComSelectDialog"></ComSelect>
    <AgentSelect v-if="showPlan2AgentDialog"></AgentSelect>
  </div>
</template>

<script>

import PlanAPI from "../../../../js/production/plan/planAPI"
import PropsAPI from "../../../../js/production/props/propsAPI"
import Validations from "../../../../js/production/validations"
import RiskKindSelect2 from "./RiskKindSelect2";
import ItemCodeSelect2 from "./ItemCodeSelect2";
import AmountPremiumAdd from "./AmountPremiumAdd";
import ComSelect from "../../common/ComSelect";
import AgentSelect from "./AgentSelect";
export default {
  components: {
    RiskKindSelect2,
    ItemCodeSelect2,
    AmountPremiumAdd,
    ComSelect,
    AgentSelect,
  },
  data() {
    return {
      dialogVisible: true,
      dialog_margin_top: '1%',
      formData: {
        plantype: '',
        risk: null,
        plancode: '',
        plancname: '',
        planename: '',
        validstatus: '1',
        delflag: '0',
        autoundwrt: '0',
        traveldestination: '',
        periodtype: '3',
        period: '',
        applycomcode: '',
        applychannel: '',
        occupationcode: '',
        autodoc : '',
        propsGroup: [],
        kindcodesGroup: [],
        kindsGroup: [],
        itemcodesGroup: [],
        itemsGroup: [],
        kinditemsGroup: [],
        originalPlan: null,
      },
      propsOptions: [],
      propsStr: '',
      propsIndex: [],
      comLabel: '',
      arrayComcodes: [],
      cacheKindItems: [],
      planTypeOptions: [
        { label: 'a-非定额', value: 'a' },
        { label: 'b-定额定险别', value: 'b' },
        { label: 'c-定险别定费率', value: 'c' },
        { label: 'd-定额定险别定费率定保费', value: 'd' },
      ],
      periodTypeOptions: [
        { label: '天', value: '3' },
      ],
      riskOptions: [],
      validOptions: [
        { label: '1-有效', value: '1' },
        { label: '0-无效', value: '0' }
      ],
      delFlagOptions: [
        { label: '1-是', value: '1' },
        { label: '0-否', value: '0' }
      ],
      autoUndwrtOptions: [
        { label: '1-是', value: '1' },
        { label: '0-否 ', value: '0' },
      ],
      autoDocOptions: [
        {label: '默认',  value: null},
        {label: 'Y-是',  value: 'Y'},
        {label: 'N-否 ',  value: 'N'},
      ],
      showRiskKindSelect2Dialog: false,
      showItemCodeSelect2Dialog: false,
      showAmountPremiumAddDialog: false,
      showComSelectDialog: false,
      showPlan2AgentDialog: false,
      disabledGroup: {
        delflag: true,
      },
      itemNo:'',
      currentKindItem: {},
      loading: false,
      currentPropsIndex: '',
      originalCom: '',			//判断方案权限适用机构是否变化
    }
  },
  mounted() {
    PlanAPI.initRiskSelect(this);
    PropsAPI.initPropsSelect(this);
    for (let i = 0; i < this.propsOptions.length; i++) {
      this.propsStr += "<option value='" + this.propsOptions[i].propscode + "'>" + this.propsOptions[i].propscname + "</option>";
    }
    let temp = Object.assign({}, this.$parent.selectedRows[0]);
    this.comLabel = temp.applycomcode;
    this.originalCom = temp.applycomcode;
    if (typeof (temp.applycomcode) !== 'undefined' && temp.applycomcode !== null && temp.applycomcode !== '') {
      this.arrayComcodes = temp.applycomcode.split(',');
    }
    temp.delflag = null;
    temp.risk = null;
    temp.propsGroup = [];
    temp.kindcodesGroup = [];
    temp.kindsGroup = [];
    temp.itemcodesGroup = [];
    temp.itemsGroup = [];
    temp.kinditemsGroup = [];
    temp.originalPlan = Object.assign({}, this.$parent.selectedRows[0]);
    this.formData = temp;
    this.formData.risk = {
      riskcode: this.formData.riskcode,
      riskversion: this.formData.riskversion,
    };
    PlanAPI.initKindItems2(this);
    if (this.formData.plantype === 'a') {
      this.disabledGroup.delflag = false;
    }
    let vm = this;
    setTimeout(function () {
      for (let i = 0; i < vm.formData.propsGroup.length; i++) {
        for (let j = 0; j < vm.formData.propsGroup[i].length; j++) {
          let id = j + 1;
          $("#propscname" + i + id).html(vm.propsStr);
          $("#propscname" + i + id).val(vm.formData.propsGroup[i][j].propscode);
          $("#propstype" + i + id).val(vm.formData.propsGroup[i][j].propstype);
          $("#propsvalue" + i + id).val(vm.formData.propsGroup[i][j].propsvalue);
          $("#startvalue" + i + id).val(vm.formData.propsGroup[i][j].startvalue);
          $("#endvalue" + i + id).val(vm.formData.propsGroup[i][j].endvalue);
          vm.propsTypeChange(i, vm.formData.propsGroup[i][j]);
        }
      }
    }, 100);
    setInterval(function () {
      if (vm.comLabel !== vm.originalCom) {
        vm.formData.applychannel = '';
        vm.originalCom = vm.comLabel;
      }
    }, 500);
  },
  watch: {
    comLabel(newVal, oldVal) {
      this.formData.applycomcode = newVal;
    }
  },
  methods: {
    add2() {
      for (let i = 0; i < this.formData.propsGroup.length; i++) {
        for (let j = 0; j < this.formData.propsGroup[i].length; j++) {
          let id = this.formData.propsGroup[i][j].rowId;
          this.formData.propsGroup[i][j].plancode = '';
          this.formData.propsGroup[i][j].riskcode = '';
          this.formData.propsGroup[i][j].riskversion = '';
          this.formData.propsGroup[i][j].propscode = $("#propscname" + i + id).val();
          this.formData.propsGroup[i][j].propstype = $("#propstype" + i + id).val();
          this.formData.propsGroup[i][j].propsvalue = $("#propsvalue" + i + id).val();
          this.formData.propsGroup[i][j].startvalue = $("#startvalue" + i + id).val();
          this.formData.propsGroup[i][j].endvalue = $("#endvalue" + i + id).val();
        }
      }
      PlanAPI.add2(this);
    },
    off() {
      this.$parent.showCopy2Dialog = false;
    },
    checkNumber(length, field) {
      Validations.checkNumber(length, this.formData, field);
    },
    newPlanCode() {
      this.formData.propsGroup = [];
      this.formData.kindcodesGroup = [];
      this.formData.kindsGroup = [];
      this.formData.itemcodesGroup = [];
      this.formData.itemsGroup = [];
      this.formData.kinditemsGroup = [];
      this.propsIndex = [];
      // PlanAPI.newPlanCode(this); // 移除原因：点击保存时才生成方案代码
    },
    openRiskKindSelect2Dialog(k) {
      if (this.formData.risk === null) {
        this.$message({ type: 'error', message: '请先选择险种代码！' });
        return;
      }
      this.currentPropsIndex = k;
      this.showRiskKindSelect2Dialog = true;
    },
    openItemCodeSelect2Dialog(k) {
      if (this.formData.kindcodesGroup[k] === '') {
        this.$message({ type: 'error', message: '请先选择条款代码！' });
        return;
      }
      this.currentPropsIndex = k;
      this.showItemCodeSelect2Dialog = true;
    },
    openAmountPremiumAddDialog(row, itemNo) {
      this.itemNo = itemNo;
      this.currentKindItem = row;
      this.showAmountPremiumAddDialog = true;
    },
    openPlan2CompanyDialog() {
      this.showComSelectDialog = true;
    },
    openPlan2AgentDialog() {
      PlanAPI.openPlan2AgentDialog(this);
    },
    setDefault() {
      switch (this.formData.plantype) {
        case 'a': {
          this.disabledGroup.delflag = false;
          break;
        }
        case 'b': {
          this.formData.delflag = '0';
          this.disabledGroup.delflag = true;
          break;
        }
        case 'c': {
          this.formData.delflag = '0';
          this.disabledGroup.delflag = true;
          break;
        }
        case 'd': {
          this.formData.delflag = '0';
          this.disabledGroup.delflag = true;
          break;
        }
      }
    },
    propsTypeChange(k, row) {
      if ($("#propstype" + k + row.rowId).val() === '1') {
        $("#single" + k + row.rowId).hide();
        $("#multi" + k + row.rowId).show();
      } else if ($("#propstype" + k + row.rowId).val() === '0') {
        $("#single" + k + row.rowId).show();
        $("#multi" + k + row.rowId).hide();
      }
    },
    addPropsGroup() {
      if (this.formData.risk === null || typeof this.formData.risk === 'undefined' || this.formData.risk === '') {
        this.$message({ type: 'error', message: '请先选择险种代码！' });
        return;
      }
      this.formData.propsGroup.push([]);
      this.propsIndex.push(0);
      this.formData.kindcodesGroup.push('');
      this.formData.kindsGroup.push([]);
      this.formData.itemcodesGroup.push('');
      this.formData.itemsGroup.push([]);
      this.formData.kinditemsGroup.push([]);
    },
    delPropsGroup(k) {
      let tmpPropsGroup = [];
      let tmpPropsIndex = [];
      for (let i = 0; i < this.formData.propsGroup.length; i++) {
        if (k !== i) {
          let tmpProps = [];
          let tempId = 1;
          for (let j = 0; j < this.formData.propsGroup[i].length; j++) {
            let id = j + 1;
            tmpProps.push({
              propscode: $("#propscname" + i + id).val(),
              propstype: $("#propstype" + i + id).val(),
              propsvalue: $("#propsvalue" + i + id).val(),
              startvalue: $("#startvalue" + i + id).val(),
              endvalue: $("#endvalue" + i + id).val(),
              rowId: tempId++
            });
          }
          tmpPropsGroup.push(tmpProps);
          tmpPropsIndex.push(this.propsIndex[i]);
        }
      }
      this.formData.propsGroup = tmpPropsGroup;
      this.propsIndex = tmpPropsIndex;

      let vm = this;
      setTimeout(function () {
        for (let i = 0; i < tmpPropsGroup.length; i++) {
          for (let j = 0; j < tmpPropsGroup[i].length; j++) {
            let id = j + 1;
            $("#propscname" + i + id).html(vm.propsStr);
            $("#propscname" + i + id).val(tmpPropsGroup[i][j].propscode);
            $("#propstype" + i + id).val(tmpPropsGroup[i][j].propstype);
            $("#propsvalue" + i + id).val(tmpPropsGroup[i][j].propsvalue);
            $("#startvalue" + i + id).val(tmpPropsGroup[i][j].startvalue);
            $("#endvalue" + i + id).val(tmpPropsGroup[i][j].endvalue);
            vm.propsTypeChange(i, tmpPropsGroup[i][j]);
          }
        }
      }, 100);

      //////////////////////////////////////////////////////////////////////////
      //条款组删除
      let tmpKindcodesGroup = [];
      let tmpKindsGroup = [];
      let tmpItemcodesGroup = [];
      let tmpItemsGroup = [];
      let tmpKinditemsGroup = [];
      for (let i = 0; i < this.formData.kinditemsGroup.length; i++) {
        if (k !== i) {
          tmpKindcodesGroup.push(this.formData.kindcodesGroup[i]);
          tmpKindsGroup.push(this.formData.kindsGroup[i]);
          tmpItemcodesGroup.push(this.formData.itemcodesGroup[i]);
          tmpItemsGroup.push(this.formData.itemsGroup[i]);
          tmpKinditemsGroup.push(this.formData.kinditemsGroup[i]);
        }
      }
      this.formData.kindcodesGroup = tmpKindcodesGroup;
      this.formData.kindsGroup = tmpKindsGroup;
      this.formData.itemcodesGroup = tmpItemcodesGroup;
      this.formData.itemsGroup = tmpItemsGroup;
      this.formData.kinditemsGroup = tmpKinditemsGroup;
      //////////////////////////////////////////////////////////////////////////

    },
    addProps(k) {
      let vm = this;
      let index = ++this.propsIndex[k];
      vm.formData.propsGroup[k].push({ rowId: index });
      setTimeout(function () {
        $("#propscname" + k + index).html(vm.propsStr);
      }, 100);
    },
    delProps(k, rowId) {
      let tempArray = [];
      let tempId = 1;
      for (let i = 0; i < this.formData.propsGroup[k].length; i++) {
        let id = this.formData.propsGroup[k][i].rowId;
        if (rowId !== id) {
          tempArray.push({
            propscode: $("#propscname" + k + id).val(),
            propstype: $("#propstype" + k + id).val(),
            propsvalue: $("#propsvalue" + k + id).val(),
            startvalue: $("#startvalue" + k + id).val(),
            endvalue: $("#endvalue" + k + id).val(),
            rowId: tempId++
          })
        }
      }
      this.propsIndex[k] = tempArray.length;
      this.formData.propsGroup[k] = tempArray;
      for (let i = 0; i < tempArray.length; i++) {
        let id = i + 1;
        $("#propscname" + k + id).val(tempArray[i].propscode);
        $("#propstype" + k + id).val(tempArray[i].propstype);
        $("#propsvalue" + k + id).val(tempArray[i].propsvalue);
        $("#startvalue" + k + id).val(tempArray[i].startvalue);
        $("#endvalue" + k + id).val(tempArray[i].endvalue);
        this.propsTypeChange(k, tempArray[i]);
      }

      //////////////////////////////////////////////////////////////////////////
      //由于Vue中数组修改不会触发重新渲染，故这里先清空数据再还原，使数组重新渲染
      let tmpPropsGroup = this.formData.propsGroup;
      this.formData.propsGroup = [];
      for (let index in tmpPropsGroup) {
        this.formData.propsGroup.push(tmpPropsGroup[index]);
      }
      //////////////////////////////////////////////////////////////////////////

    }
  }
}
</script>
